﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataMongo.Entities;
using ExtendedMongoMembership.Helpers;
using DataMongo;
using System.IO;
using MVCMongo.ViewModel.Albums;
using WebMatrix.WebData;

namespace MVCMongo.Controllers
{
    public class AlbumController : Controller
    {
        private int userId = WebSecurity.GetUserId(WebSecurity.CurrentUserName);
        //
        // GET: /Album

        public ActionResult Album()
        
        {
            var con = new RepositoryBaseMongo("Album");
            var data = con.GetAll<Album>().Where(x=>x.UserId==userId);
            return View("Album","~/Views/Shared/_LayoutProfile.cshtml",data);
        }

        public ActionResult AlbumAdd()
        {
            var con = new RepositoryBaseMongo("Album");
            var album = new Album();
            return View(album);
            
        }
        [HttpPost]
        public ActionResult AlbumAdd(Album model, List<string> picture)
        {

            // Album Add 
            var con = new RepositoryBaseMongo("Album");
            int id = 0;
            var albums = con.GetAll<Album>().ToList();         
            if (albums.Any())
                id = albums.Max(x => x.AlbumId);
            id += 1;

            model.AlbumId = id;
            model.UserId = userId;
            con.InsertOrUpdate(model);


            // photos Add
            var files = picture.Count(x => x != null);
            if (files != 0)
            {

                foreach (var file in picture)
                {
                     int photoId = 0;
                     var conP = new RepositoryBaseMongo("Photos");
                    var photoList = conP.GetAll<Photos>().ToList();
                    if (photoList.Any())
                       photoId  = photoList.Max(x => x.PhotoId);
                    photoId += 1;
                    var photos = new Photos();
                    photos.AlbumId = model.AlbumId;
                    photos.PhotoId = photoId;
                    photos.PhotoUrl = file;
                    var directory = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\UserUploadedPic\\Albums\\" + model.AlbumId + "\\" ;
                        if (!Directory.Exists(directory))
                            Directory.CreateDirectory(directory);


                    directory = Path.Combine(directory, file);
                     var path = Server.MapPath(Url.Content("~/Content/AlbumImageTemp/" + file));

                     

                     System.IO.File.Move(path, directory);
                      conP.InsertOrUpdate(photos);
                   



                }
                //for (int i = 0; i < files; i++)
                //{
                //    int photoId = 0;
                //    var file = Request.Files[i];
                //    var conP = new RepositoryBaseMongo("Photos");
                //    var photoList = conP.GetAll<Photos>().ToList();
                //    if (photoList.Any())
                //       photoId  = photoList.Max(x => x.PhotoId);
                //    photoId += 1;
                //    var photos = new Photos();
                //    photos.AlbumId = model.AlbumId;
                //    photos.PhotoId = photoId;
                    
                //        var directory = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\UserUploadedPic\\Albums\\" + model.AlbumId + "\\";
                //        if (!Directory.Exists(directory))
                //            Directory.CreateDirectory(directory);
                //        photos.PhotoUrl = Path.GetFileName(file.FileName);
                //        var path = Path.Combine(Server.MapPath("~/Content/UserProfile/UserUploadedPic/Albums/" + model.AlbumId + "/"), photos.PhotoUrl);
                //        file.SaveAs(path);
                    
                //    conP.InsertOrUpdate(photos);

                   
                }

                // add in userPost

                var connection = new RepositoryBaseMongo("UserPost");

                int Id = 0;
                var sources = connection.GetAll<Post>().ToList();
                var postViewModel = new Post();
                if (sources.Any())
                    Id = sources.Max(x => x.PostId);
                Id += 1;
                postViewModel.PostedBy = userId;
                postViewModel.PostedDate = DateTime.UtcNow;
                postViewModel.PostId = Id;
                postViewModel.NoOfPhotoUpload = files;
                postViewModel.Source = "added a new Photo";
            postViewModel.AlbumId = id;
               
                connection.InsertOrUpdate(postViewModel);
            
           
         return RedirectToAction("Album");


           
        }
        public ActionResult AlbumEdit(int id)
        {
            var viewModel = new AlbumListViewModel();
            var con = new RepositoryBaseMongo("Album");
            var conF = new RepositoryBaseMongo("Photos");
            viewModel.Album = con.GetAll<Album>().FirstOrDefault(x => x.AlbumId == id);
            viewModel.Photos = conF.GetAll<Photos>().Where(x => x.AlbumId == id).ToList();

            return View(viewModel);
            
        }
        [HttpPost]

        public ActionResult AlbumEdit(Album album, List<string> picture)
        {
            var con = new RepositoryBaseMongo("Album");
            List<Album> list = (from f in con.GetAll<Album>()
                                where f.AlbumId == album.AlbumId
                                select f).ToList();
            Album albums = new Album();
            if (list.Count > 0) albums = list[0];
            album._id = albums._id;
            album.UserId = userId;

            con.InsertOrUpdate(album);

            // photos Add
            var files = picture.Count(x => x!= null);
            if (files != 0)
            {
                foreach (var file in picture)
                {
                    int photoId = 0;
                    var conP = new RepositoryBaseMongo("Photos");
                    var photoList = conP.GetAll<Photos>().ToList();
                    if (photoList.Any())
                        photoId = photoList.Max(x => x.PhotoId);
                    photoId += 1;
                    var photos = new Photos();
                    photos.AlbumId = album.AlbumId;
                    photos.PhotoId = photoId;
                    photos.PhotoUrl = file;
                    var directory = AppDomain.CurrentDomain.BaseDirectory + "Content\\UserProfile\\UserUploadedPic\\Albums\\" + album.AlbumId + "\\";
                    if (!Directory.Exists(directory))
                        Directory.CreateDirectory(directory);


                    directory = Path.Combine(directory, file);
                    var path = Server.MapPath(Url.Content("~/Content/AlbumImageTemp/" + file));



                    System.IO.File.Move(path, directory);
                    conP.InsertOrUpdate(photos);




                }
                // add in userPost

                var connection = new RepositoryBaseMongo("UserPost");

                int Id = 0;
                var sources = connection.GetAll<Post>().ToList();
                var postViewModel = new Post();
                if (sources.Any())
                    Id = sources.Max(x => x.PostId);
                Id += 1;
                postViewModel.PostedBy = userId;
                postViewModel.PostedDate = DateTime.UtcNow;
                postViewModel.PostId = Id;
                postViewModel.NoOfPhotoUpload = files;
                postViewModel.Source = "added a new Photo";
                postViewModel.AlbumId = album.AlbumId;
                connection.InsertOrUpdate(postViewModel);
            }

            return RedirectToAction("Album");
        }


        [HttpPost]
        public ActionResult UploadImages(IEnumerable<HttpPostedFileBase> attachments)
        {
            var imgGuid = string.Empty;
            var fileName = string.Empty;
            var fileext = string.Empty;
            var filenamewithoutext = string.Empty;
            var thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Content\\AlbumImageTemp\\";
            foreach (var file in attachments)
            {
                fileext = Path.GetExtension(file.FileName).ToLower();
                filenamewithoutext = Path.GetFileNameWithoutExtension(file.FileName);
                if (fileext != ".jpg" && fileext != ".png" && fileext != ".jpeg") continue;
                imgGuid = Guid.NewGuid().ToString();
                var coverfilename = imgGuid + fileext;
                var path = AppDomain.CurrentDomain.BaseDirectory + "Content\\AlbumImageTemp\\";
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                path = Path.Combine(path, coverfilename);
                file.SaveAs(path);


                //_filehelp.ConvertToThumbnail(file, imgGuid + "_th", fileext, thumbpath);
                fileName = imgGuid + fileext;
                //thumbpath += imgGuid + "_th" + fileext;
            }
            var imagepath = "/Content/AlbumImageTemp/" + imgGuid + fileext;
            var view = RenderPartialViewToString("_partialImageTemp", imagepath);
            var res = Json(new { guid = imgGuid, view=view,filename = fileName, ext = fileext, filenamewithoutext = filenamewithoutext, path = imagepath });

            return res;
        }

        public ActionResult DeleteImageTemp(string image)
        {
            try
            {
                var path = Server.MapPath(Url.Content("~/Content/AlbumImageTemp/" + image));
                System.IO.File.Delete(path);
                return Json("true", JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                return Json("false", JsonRequestBehavior.AllowGet);
            }
         
        }
        public string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
        public ActionResult PhotoDelete(int photoId, string con)
        {
            var conn = new RepositoryBaseMongo("Photos");
            var list = conn.GetAll<Photos>().ToList().FirstOrDefault(x => x.PhotoId==photoId);

            conn.Delete<Photos>(list._id);
           return RedirectToAction(con, new{id=list.AlbumId});

        }



       
        public ActionResult AlbumDetails(int Id)
        {
            var con = new RepositoryBaseMongo("Photos");
            var conA = new RepositoryBaseMongo("Album");
            var data = con.GetAll<Photos>().Where(x=>x.AlbumId==Id);
            ViewBag.AlbumName = conA.GetAll<Album>().Where(x => x.AlbumId == Id).Select(x => x.Name).FirstOrDefault();


            return View(data);

        }

           
          

        }
   


        }

        
            
     
    

